// 加载中提示
var loader = "<div class='loading' style='margin:0 auto;text-align:center; padding-top:20px;'><img src='/cwp/src/assets/img/loading/cmcc_loading_lg.gif' style='height:35px;width:35px;display:inline;' alt=''/><p style='font-size:12px;display:block;margin-top: 10px'>载入中，请稍候...</p></div>";

//树形节点点击添加
var countTreeId;
$(function(){
    initBuildingTree();
});

//验证
$(document).ready(function () {
    $.formValidator.initConfig({
        formid: "frmMain", onerror: function (msg) {return false;}, onsuccess: function () {return true;}
    });
    $("#assetTypeCode").formValidator({
        onfocus: "请输入资产类型编码",
        oncorrect: " "
    }).InputValidator({
        min: 1,
        max: 100,
        onempty: "请输入资产类型编码",
        onerror: "请输入资产类型编码"
    });
    $("#assetTypeName").formValidator({
        onfocus: "请输入资产类型名称",
        oncorrect: " "
    }).InputValidator({
        min: 1,
        max: 100,
        onempty: "请输入资产类型名称",
        onerror: "请输入资产类型名称"
    });

});

//获取列表树数据
function initBuildingTree(){
	$("#treeOrg").html(loader);
    $.getJSON('/cwp/src/json/system/assetType/assetType_004.json',function(data){
        successResultBuilding(data);
    })

    // PostForm("/cwp/front/sh/assetType!execute", "uid=asset004x", "", successResultBuilding, '',"frmTree");
}

function successResultBuilding(result){
    switch (result.returnCode) {
        case "0":
            $("#dataTreeTotal").text( "共"+ result.beans.length +"条记录");
            if(result.beans.length>0) {
                constructTree(result.beans);
            }
            break;
        case "1":
            tipModal("icon-cross", "资产类型树获取失败");
            break;
        case "-9999":
            tipModal("icon-cross", "资产类型树获取失败");
            break;
        default:
            break;
    }
}

//资产类型类型选择
$("#buildingType").on("change",function(){
    if($(this).val() == "0"){
        $("#parentText").val("");
        $("#parentId").val("");
        $(".pnode").hide();
    }
    else{
        $(".pnode").show();
    }
});

//1、判断资产类型为区域
//2、根据父ID归类
//3、
//重构树对象数据
function constructTree(data){
    var zNodes=[];
    for(var i=0; i<data.length; i++){
        var obj = new Object();
        obj.id = data[i].assetTypeId;
        obj.pId = data[i].parentId;
        
     // 根据nodeType类型 设置 类型名称及编码
        obj.type = data[i].nodeType;
        if(obj.type == 4){
        	obj.name=data[i].funName;
            obj.code=data[i].funCode;
        }
        else if(obj.type == 3){
        	obj.name=data[i].typeName;
            obj.code=data[i].typeCode;
        }
        else if(obj.type == 2){
        	obj.name=data[i].sysName;
            obj.code=data[i].sysCode;
        }
        else if(obj.type == 1){
        	obj.name=data[i].parkName;
            obj.code=data[i].parkCode;
        }
        zNodes.push(obj);
    }

    var setting = {
        view: {
            showIcon: false,
            selectedMulti: false,
            addDiyDom:addDiyDom
        },
        data: {
            simpleData: {
                enable: true
            }
        }
    };
    $.fn.zTree.init($("#treeOrg"), setting, zNodes);
    var zTree = $.fn.zTree.getZTreeObj("treeOrg");
    if(countTreeId!=undefined && countTreeId!=""){
        var getTreeNode=zTree.getNodeByTId(countTreeId);
        //默认选中节点
        zTree.selectNode(getTreeNode);
        //默认展开节点
        zTree.expandNode(getTreeNode,true);
    }
    //添加表头
    var li_head=' <li class="head"><a><div class="diy">资产类型名称</div><div class="diy">资产类型编码</div>' +
        '<div class="diy">操作</div><div class="diy"></div></a></li>';
    var rows = $("#treeOrg").find('li');
    if(rows.length>0){
        rows.eq(0).before(li_head)
        $("#dataTreeData").remove();
    }else{
        $("#treeOrg").append(li_head);
        $("#treeOrg").append('<li><td style="text-align: center;line-height: 30px;" >无符合条件数据</li>')
    }
}
;

//新增保存
$("#btn_saveUser").on("click",function(){
    //判断表单验证是否通过
    if($.formValidator.PageIsValid()){
        var buildingId=$("#hidAssetTypeId").val();
        if(buildingId==""){
            PostForm("/cwp/front/sh/assetType!execute", "uid=asset007x", "post", successResultSaveBuilding, '',"frmMain");
        }
        else{
            PostForm("/cwp/front/sh/assetType!execute", "uid=asset002x", "post", successResultEditBuilding, '',"frmMain");
        }
    }
});

//新增请求成功回调函数
function successResultSaveBuilding(result) {
    switch (result.returnCode) {
        case "0":
            $("#modalDistrict").modal("hide");
            tipModal("icon-checkmark", "保存成功");
            initBuildingTree();
            break;
        case "1":
            tipModal("icon-cross", result.returnMessage);
            break;
        case "-9999":
            tipModal("icon-cross", "保存失败");
            break;
        default:
            break;
    }
}

//编辑资产类型信息回调
function successResultEditBuilding(result){
    switch (result.returnCode) {
        case "0":
            $("#modalDistrict").modal("hide");
            tipModal("icon-checkmark", "保存成功");
            initBuildingTree();
            break;
        case "1":
            tipModal("icon-cross", result.returnMessage);
            break;
        case "-9999":
            tipModal("icon-cross", "保存失败");
            break;
        default:
            break;
    }
}

function beforeRemove(id) {
    $("#assetTypeId").val(id.getAttribute("data-id"));
    $("#modalDelBuilding").modal({//启用modal ID
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
    $(window).on('resize', centerModal());
    return false;
}

//删除节点
$("#btnDelete").on("click",function(){
    PostForm("/cwp/front/sh/assetType!execute", "uid=asset003x", "", delBuildingbyId, "","frmTree");
});

function delBuildingbyId(result){
    $("#modalDelBuilding").modal("hide");
    switch (result.returnCode) {
        case "0":
            tipModal("icon-checkmark", "删除成功");
            initBuildingTree();
            break;
        case "1":
            tipModal("icon-cross", result.returnMessage);
            break;
        case "-9999":
            tipModal("icon-cross", "删除失败");
            break;
        default:
            break;
    }
}

//编辑
function beforeEditName(id) {
    updateAssetTreeModal(id.getAttribute("data-id"));
    // setTimeout(function() {
    //     $("#assetTypeId").val(id.getAttribute("data-id"));
    //     PostForm("/cwp/front/sh/assetType!execute", "uid=asset001x", "", getBuildingById, '',"frmTree");
    // }, 0);
      modalDistrict();
    return false;
}

//显示资产类型详情
function getBuildingById(result){
    modalDistrict();
    var data = result.object;
    $("#modalDistrict .modal-title").html("编辑资产类型");
    switch (result.returnCode) {
        case "0":
        	$("#hidAssetTypeId").val(data.assetTypeId);
            $("#parentId").val(data.parentId);
            if(result.object.parentId != 0){
                $("#parentText").val(data.parentAssetTypeName);
            }else{
                $("#parentText").val("")
            }
            $("#rank").val(data.rank);
            
            // 根据nodeType类型 设置 类型名称及编码
            if(data.nodeType == 4){
            	$("#assetTypeCode").val(data.funCode);
            	$("#assetTypeName").val(data.funName);
            }
            else if(data.nodeType == 3){
            	$("#assetTypeCode").val(data.typeCode);
            	$("#assetTypeName").val(data.typeName);
            }
            else if(data.nodeType == 2){
            	$("#assetTypeCode").val(data.sysCode);
            	$("#assetTypeName").val(data.sysName);
            }else if(data.nodeType == 1){
            	$("#assetTypeCode").val(data.parkCode);
            	$("#assetTypeName").val(data.parkName);
            }
            $("#nodeType").val(data.nodeType);
            break;
        case "1":
            tipModal("icon-cross", result.returnMessage);
            break;
        case "-9999":
            tipModal("icon-cross", "获取详情失败");
            break;
        default:
            break;
    }
}

//打开模态框
function modalDistrict(){
    //$("#modalAddDistrict").html(modal);
    $(".tipArea div").html("").attr("class","");
    $("#modalDistrict .modal-title").html("新增资产类型");
    $("#hidAssetTypeId").val("");
    $("#nodeType").val("1");
    $("#parentText").val("");
    $("#parentId").val("");
    $("#rank").val("");
    $("#assetTypeCode").val("");
    $("#assetTypeName").val("");
    $("#assetTypeType").val("");
    $("#assetTypeArea").val("");
    $("#assetTypeHeigh").val("");
    $("#assetTypeState").val("");
    $("#assetTypeDescription").val("");
    $("#modalDistrict").modal({
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
    $(window).on('resize', centerModal());
}

//点击节点事件
function beforeClick(treeId, treeNode){
    var buildingId=treeNode.id;
    $("#buildingId").val(buildingId);
    isFirst=true;
    //searchUserList(1);
}

//新增
$('#btnAddBuilding').on("click",function(){
    modalDistrict();
    addDeptTreeModal();
});


//自定义DOM节点
function addDiyDom(treeId, treeNode) {
    countTreeId = treeNode.tId;
    var spaceWidth = 15;
    var liObj = $("#" + treeNode.tId);
    var aObj = $("#" + treeNode.tId + "_a");
    var switchObj = $("#" + treeNode.tId + "_switch");
    var icoObj = $("#" + treeNode.tId + "_ico");
    var spanObj = $("#" + treeNode.tId + "_span");
    aObj.attr('title','');
    aObj.append('<div class="diy swich"></div>');
    var div = $(liObj).find('div').eq(0);
    switchObj.remove();
    spanObj.remove();
    icoObj.remove();
    div.append(switchObj);
    div.append(spanObj);
    $("#" + treeNode.tId + "_span").text(treeNode.buildingDesc);
    var spaceStr = "<span style='height:1px;display: inline-block;width:" + (spaceWidth * treeNode.level) + "px'></span>";
    switchObj.before(spaceStr);
    var editStr = '';
    editStr += '<div class="diy">' + (treeNode.code )+ '</div>';
    //修改功能暂时关闭
    editStr += '<div class="diy"><a class="t-btn t-btn-sm t-btn-red t-btn-deal btnDelete tree-btnred" onclick="beforeRemove(this)" data-tid="'+ treeNode.tId +'"   data-id="'+ treeNode.id +'">删除</a><a class="t-btn t-btn-sm t-btn-blue t-btn-deal editDictData tree-btnblue" onclick="beforeEditName(this)"  data-tid="'+ treeNode.tId +'"   data-id="'+ treeNode.id +'" >编辑</a></div><div class="diy">'+"　"+'</div>';
    aObj.append(editStr);
    $("#" + treeNode.tId + "_a").on("click",function(){
        $("#parentId").val(treeNode.id);
    })
}

// 修改 - 资产类型树
function updateAssetTreeModal(id){
	$("#assetTypeId").val(id);
	PostForm("/cwp/front/sh/assetType!execute", "uid=asset005x", "", getDeptTreeModal, '',"frmTree");
}

//新增 - 资产类型树
function addDeptTreeModal(){
    PostForm("/cwp/front/sh/assetType!execute", "uid=asset006x", "", getDeptTreeModal, '',"frmTree");

}

//获取数据初始化部门树
function getDeptTreeModal(result){
	var data = result.beans;
    var zNodes=[];
    for(var i=0; i<data.length; i++){
        var obj = new Object();
        obj.id = data[i].assetTypeId;
        obj.pId = data[i].parentId;
        obj.type = data[i].nodeType;
        if(obj.type == 4){
        	obj.name=data[i].funName;
            obj.code=data[i].funCode;
        }
        else if(obj.type == 3){
        	obj.name=data[i].typeName;
            obj.code=data[i].typeCode;
        }
        else if(obj.type == 2){
        	obj.name=data[i].sysName;
            obj.code=data[i].sysCode;
        }
        else if(obj.type == 1){
        	obj.name=data[i].parkName;
            obj.code=data[i].parkCode;
        }
        zNodes.push(obj);
    }

    if(result.returnCode=="0"){
        //配置组织结构树
        var setting = {
            view: {
                dblClickExpand: false,
                showIcon: false,                 //隐藏节点图标
                selectedMulti: false             //设置是否允许同时选中多个节点
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                beforeClick: beforeClickSelect
            }
        };

        $.fn.zTree.init($("#treeOrgModal"), setting, zNodes);
        var zTree = $.fn.zTree.getZTreeObj("treeOrgModal");
        if(countTreeId!=undefined && countTreeId!=""){
            var getTreeNode=zTree.getNodeByTId(countTreeId);
            //默认选中节点
            zTree.selectNode(getTreeNode);
            //默认展开节点
            zTree.expandNode(getTreeNode,true);
        }
    }
}

//渲染新增部门树
function beforeClickSelect(treeId, treeNode) {
    // var zTree = $.fn.zTree.getZTreeObj("treeOrgModal");
    $("#parentText").val(treeNode.name);
    $("#parentText").blur();
    $("#parentId").val(treeNode.id);
    $("#nodeType").val(parseInt(treeNode.type) + parseInt(1));
    hideMenu();
    return false;
}

$("#parentText").on("focus",function(){
    showMenu();
});

//显示部门树
function showMenu() {
    var deptIdObj = $("#parentText");
    var deptIdOffset = $("#parentText").offset();
    //$("#menuContent").slideDown("fast");
    $("#menuContent").css({left:deptIdOffset.left + "px", top:deptIdOffset.top + deptIdObj.outerHeight() + "px"}).slideDown("fast");
    $("body").bind("mousedown", onBodyDown);
}

//隐藏部门树
function hideMenu() {
    $("#menuContent").fadeOut("fast");
    $("body").unbind("mousedown", onBodyDown);
}
function onBodyDown(event) {
    if (!(event.target.id == "parentText" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
        hideMenu();
    }
}
